import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
/**
 * 后续遍历节点并过滤，从根节点起始返回匹配节点
 * 如果子节点匹配，就认为父节点也匹配，因此不是每个节点均会调用 callback
 * @param treeNodes
 * @param callback
 * @param options
 * @returns
 */
var filter = function filter(treeNodes, callback, options) {
  var _ref = options || {},
    _ref$level = _ref.level,
    level = _ref$level === void 0 ? 0 : _ref$level,
    _ref$childrenKey = _ref.childrenKey,
    childrenKey = _ref$childrenKey === void 0 ? 'children' : _ref$childrenKey,
    parent = _ref.parent;
  var filteredTreeNodes = [];
  var internalFilter = function internalFilter(nodes, result, options) {
    var _ref2 = options || {},
      _ref2$level = _ref2.level,
      level = _ref2$level === void 0 ? 0 : _ref2$level,
      parent = _ref2.parent;
    nodes.forEach(function (node, index) {
      // 遍历子节点
      var children = node[childrenKey];
      if (children !== null && children !== void 0 && children.length) {
        var filteredChildren = [];
        internalFilter(children, filteredChildren, {
          level: level + 1,
          parent: node
        });
        if (!filteredChildren.length) {
          if (callback(node, {
            level: level,
            isMaybeLeaf: false,
            index: index,
            parent: parent
          })) {
            result.push(_objectSpread(_objectSpread({}, node), {}, _defineProperty({}, childrenKey, node[childrenKey] === null ? null : undefined)));
          }
          return;
        }
        return result.push(_objectSpread(_objectSpread({}, node), {}, _defineProperty({}, childrenKey, filteredChildren)));
      }
      if (callback(node, {
        level: level,
        isMaybeLeaf: true,
        index: index,
        parent: parent
      })) {
        return result.push(_objectSpread(_objectSpread({}, node), {}, _defineProperty({}, childrenKey, node[childrenKey] === null ? null : undefined)));
      }
    });
  };
  internalFilter(treeNodes, filteredTreeNodes, {
    level: level,
    parent: parent
  });
  return filteredTreeNodes;
};
export default filter;